//引入必要模块
const express = require('express');
const mysql = require('../mysql');

//建立路由组
const router = express.Router();

//根据关键字查找一级商品
router.get('/flist/:key', (req, res) => {
    let key = req.params.key;
    // console.log(key);
    let sql = '';
    if (key == 'all') {
        sql = 'select * from sh_product LIMIT 0,15';
    } else if (key == 'new') {
        sql = 'select * from sh_product where is_new=1 LIMIT 0,15';
    } else {
        sql = 'select * from sh_product where fCid=? LIMIT 0,15';
    }
    mysql.query(sql, [key], (err, result) => {
        if (err) throw err;
        if (result) {
            if (result.length != 0) {
                return res.send(result);
            }
            res.send('0');
        }
    });
});

//根据关键字查找二级商品
router.get('/slist/:key', (req, res) => {
    let key = req.params.key;
    let sql = 'select * from sh_product where sCid=? LIMIT 0,15';
    mysql.query(sql, [key], (err, result) => {
        if (err) throw err;
        if (result) {
            if (result.length != 0) {
                return res.send(result);
            }
            res.send('0');
        }
    });
});

//根据商品id查找商品
router.get('/detail/:pid', (req, res) => {
    let pid = req.params.pid;
    let sql = 'select * from sh_product where pid=?';
    mysql.query(sql, [pid], (err, result) => {
        if (err) throw err;
        if (result) {
            if (result.length != 0) {
                return res.send(result);
            }
            res.send('0');
        }
    });
});

//加入购物车
router.post('/cart', (req, res) => {
    let body = req.body;

    mysql.query('insert into sh_cart set ?', [body], (err, result) => {
        if (err) throw err;
        if (result.affectedRows != 0) {
            return res.send('1');
        }
        res.send('0');
    });
});

//购物车获取商品数据
router.get('/cart_detail/:uid', (req, res) => {
    let uid = req.params.uid;
    let sql = 'select sh_cart.*,sh_product.* from sh_product inner join sh_cart on sh_cart.pid = sh_product.pid where sh_cart.uid=?';
    mysql.query(sql, [uid], (err, result) => {
        if (err) throw err;
        if (result) {
            if (result.length != 0) {
                return res.send(result);
            }
            res.send('0');
        }
    });
});

//删除购物车数据
router.get('/cart_delete/:id',(req,res)=>{
    let body = req.params;

    mysql.query('delete from sh_cart where cart_id=?',[body.id],(err,result)=>{
        if(err) throw err;
        if(result.affectedRows!=0){
            return res.send('1');
        }
        res.send('0');
    });
});

//更新购物车商品数量
router.post('/cart_num',(req,res)=>{
    let body = req.body;
    console.log(body);
    
    mysql.query('update sh_cart set ? where cart_id=?',[body,body.cart_id],(err,result)=>{
        if(err) throw err;
        if(result.affectedRows!=0){
            return res.send('1');
        }
        res.send('0');
    });
});

//导出路由组
module.exports = router;